from flask_restful import Resource

from restful.api__.public__.info.atomic.RoleInfo import RoleInfo
from restful.api__.public__.info.composite.post.list._PostsList import _PostsList
from restful.api__.session import login_required_current_user_generate
from restful.model.query import QueryMultipleInstances, QueryOneInstance
from restful.model.tables import Check, Blog, Role
from restful.response import ResponseSuccess


class PostsListBySimilar(Resource):
    @login_required_current_user_generate
    def get(self, current_user):
        role = RoleInfo().get(uid=current_user.id)[0]['data']
        roless = QueryMultipleInstances(Role,{'role':role['role']})

        uids = [i.id for i in roless if i.id != current_user.id]

        posts=[]
        for i in uids:
            checks = QueryMultipleInstances(Check, {'checked': True, 'passed': True,'uid':i})

            for j in checks:
                blog = QueryOneInstance(Blog,{'id':j.pid})
                if blog:
                    posts.append(blog)


        posts_data = _PostsList(posts)
        sorted_posts = sorted(posts_data, key=lambda x: x['time'], reverse=True)
        return ResponseSuccess(data=sorted_posts)
